package com.asj.receiver;

import static android.content.Context.BIND_AUTO_CREATE;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_deviceCode;
import static com.asj.enums.HttpRequestDictEnums.receiveNetworkLogInfo;
import static com.asj.service.ReceiveMsgService.NETWORKSTATE;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;

import com.asj.MainActivity;
import com.asj.service.ReceiveMsgService;
import com.asj.service.oppoSdk.OPPOControlService;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.service.request.RequestMDMService;
import com.asj.utils.CommonsUtils;
import com.asj.utils.HttpRequestUtils;
import com.google.gson.JsonObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 监听网络状态
 * */
public class NetworkChangeReceiver extends BroadcastReceiver {
    private static final Logger log = LoggerFactory.getLogger(NetworkChangeReceiver.class);


    private static  NetworkChangeReceiver networkChangeReceiver;

    private static  LocalDateTime networkOutageLocalDateTime;
    private static  LocalDateTime networkConnectLocalDateTime;
    private static int count = 1;
    @SuppressLint("StaticFieldLeak")
    private static Context centerContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            // 网络已连接
            System.out.println("网络已连接！");
            networkLog(true);
        } else {
            System.out.println("网络已断开！");
            networkLog(false);
            CommonsUtils.showNotification(context,"网络已断开","建议连接上网络使用设备");
        }
    }

    public void networkLog(boolean isNetwork){
        count++;
        System.out.println("当前次数是多少！"+count);
        if(isNetwork){
            //设置网络网络当前连接
            networkConnectLocalDateTime = LocalDateTime.now();
        }else{
            networkOutageLocalDateTime = LocalDateTime.now();
        }
        if(networkOutageLocalDateTime != null && networkConnectLocalDateTime != null && count >= 3){
            int timeSecond =   networkConnectLocalDateTime.getSecond() - networkOutageLocalDateTime.getSecond();

            JsonObject requestParam = new JsonObject();
            requestParam.addProperty("timeCount",String.valueOf(timeSecond));
            requestParam.addProperty("outageTime",String.valueOf(networkOutageLocalDateTime));
            requestParam.addProperty("connectionTime",String.valueOf(networkConnectLocalDateTime));
            requestParam.addProperty(json_key_deviceCode.getValue(),CommonsUtils.getDeviceCode(new OPPOSDKService(centerContext).getIMEI()));
            //发生网络变化，就将情况发送给后端接收
            try{
                new Thread(()-> HttpRequestUtils.retryHttpRequest(receiveNetworkLogInfo.getValue(), requestParam.toString(), 200, 3, centerContext)).start();
            }catch (Exception e){
                log.error("发送网络波动状态请求异常！::{}",e.getMessage());
            }
        }
    }


    /**
     * 注册网络状态监听器
     * */
    public static void startListening(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        if(networkChangeReceiver == null){
            networkChangeReceiver = new NetworkChangeReceiver();
            context.registerReceiver(networkChangeReceiver, filter);
            log.warn("网络监听器已注册");
            CommonsUtils.showNotification(context,"网络监听已设置","这将会监听您设备的网络情况");
            //赋予值
            centerContext = context;
        }
    }

    /**
     * 销毁网络状态监听器
     * */
    public static void stopListening(Context context) {
        if(networkChangeReceiver != null){
            context.unregisterReceiver(networkChangeReceiver);
            log.warn("网络监听器已销毁");
        }
    }
}